#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年8月11日

@author: chenyongbing
'''
from kazoo.client import KazooClient
import argparse,sys

class KafkaDeamon(object):
    '''
    classdocs
    '''


    def __init__(self,zookeeper='127.0.0.1:2181',creating=False,delete=False):
        '''
        Constructor
        '''
        self.zookeeper = zookeeper
        try:
            self.zk = KazooClient(zookeeper)
        except Exception,error:
            print "Unknow - %s."%error.message
            sys.exit(3)
        self.creating = creating
        self.delete = delete
    def broker_deamon(self,brokers):
        NotExistsBrokers = []
        try:
            self.zk.start()
        except:
            print "Unknow - Connect To Zookeeper Error."
            sys.exit(3)
        for broker in brokers:
            if self.zk.exists('/brokers/ids/%s'%broker):
                #print '%s exists'%broker
                pass
                if self.delete:
                    print 'delete broker %s'%broker
                    self.zk.delete('/brokers/ids/%s'%broker)
            else:
                NotExistsBrokers.append(broker)
                if self.creating:
                    self.zk.create('/brokers/ids/%s'%broker)
                
                
                #print broker,'Not Exists.'
        try:
            self.zk.stop()
        except:pass
        if len(NotExistsBrokers)==0:
            print "OK - Brokers [%s] Is Normal On Zookeeper %s."%(','.join(brokers),self.zookeeper)
            sys.exit(0)
        else:
            print "CRITICAL - Brokers [%s] Is Not Exists On Zookeeper %s."%(','.join(brokers),self.zookeeper)
            sys.exit(2)
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--zookeeper', metavar=u'zookeeper ', default='192.168.1.203:2181')
    parser.add_argument('--brokers', metavar=u'brokers', required=True)
    parser.add_argument('--create',action='store_true',help='create')
    parser.add_argument('--delete',action='store_true',help='delete')
    args = parser.parse_args()
    zookeeper = args.zookeeper
    brokers = args.brokers
    creating = args.create
    delete = args.delete
    myKafkaDeamon = KafkaDeamon(zookeeper,creating,delete)
    myKafkaDeamon.broker_deamon(brokers.split(','))
    
    
    
    